const express  = require('express')
const bodyParser = require('body-parser')
const fileupload = require('express-fileupload')
const app = express()
const {extname,resolve} =  require('path')
const {existsSync,appendFileSync,writeFileSync} = require('fs')

app.all('*',(req,res,next) => {
    res.header('Access-Control-Allow-origin','*')
    res.header('Access-Control-Allow-Methods','POST,GET')
    next() // 执行中间件
}) // 解决跨域问题

app.use(bodyParser.urlencoded({extended:true}))
app.use(fileupload())
app.use(bodyParser.json())
app.use('/',express.static('uploadTemp'))

app.post('/file/upload',(req,res) => {
    const UPLOADTYPE = {
        'video/mp4':'mp4',
        'video/mp3':'mp3'
    }
    console.log(req)
    let  {name,type,fileName,size,uploadSize} =  req.body
    let { file } = req.files
    if(!file) {
        res.send({
            code:101,
            msg:'NO file upload'
        })
        return
    }
    if(!UPLOADTYPE[type]) {
        res.send({
            code:102,
            msg:'the type is not allowed for uploading.'
        })
        return
    }

    let  nameFile = fileName + extname(name) // path 模块取文件的后缀名
    const  filePath = resolve(__dirname,  './uploadTemp/' + nameFile)
    console.log(name,file,nameFile)

    if(uploadSize !== '0' ) { // 有文件大小进行文件追加操作
         if(!existsSync(filePath)) {
             res.send({
                 msg:"no file exists",
                 code:1003
             })
             return;
         }
         appendFileSync(filePath,file.data)
         res.send({
            msg:"appended",
            code:0,
            fileUrl:'http://localhost:8000/' + nameFile
        })
        return;
    }

    writeFileSync(filePath,file.data)


    res.send({
        msg:"file is create",
        code:0
    })
})

const PORT  = 8000
app.listen(PORT , () => {
    console.log('启动了',PORT)
}) // 监听端口号
